//
//  AppDelegate.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/2.
//

import UIKit
import SwiftyStoreKit
import RxAlamofire
import Alamofire
import RxSwift
import RxCocoa
import AliyunPlayer
import XHLaunchAd

import Bugly

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        // 百度统计
//        BaiduMobStat.default().start(withAppId: "b0266dd6e4") // 设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
//        #if DEBUG
//        BaiduMobStat.default().enableDebugOn = true
//        #endif
        
        //Bug
//        Bugly.start(withAppId: "0d417d7dd3")
        Bugly.start(withAppId: "0a614fdb28")
        AliPlayer.setEnableLog(false)
        //创建下载目录
        XS_DownloadManager.createDirectory()
        //继续下载之前没下载完成的课程
        if isOpenResumeDownload {
            XS_DownloadManager.shared.resumeDownload()
        }
        //是否允许流量看视频
        UserDefaults.standard.set(true, forKey: .xsKey_videoAllowCellar)
        UserDefaults.standard.synchronize()
        //私密下载
        let encrptyFilePath = Bundle.main.path(forResource: "encryptedApp", ofType: "dat")
        AliPrivateService.initKey(encrptyFilePath)
        registerShare()
        window = getWindow()
        //内购
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:
                    if purchase.needsFinishTransaction {
                        // Deliver content from server, then:
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                // Unlock content
                case .failed, .purchasing, .deferred:
                    break // do nothing
                default:
                    break
                }
            }
        }
//        XHLaunchAd.setLaunch(.launchScreen)
//        XHLaunchAd.setWaitDataDuration(3)
//        XS_NetWork.requestJson("/setting/querySettings")
//            .mapModel(type: XS_SettingModel.self) // 返回 模型对象 和原始数据
//            .subscribe(onNext: { model, resp in
//                XS_Singleton.shared.settingModel = model
//                //启动图
//                let config = XHLaunchImageAdConfiguration.default()
//                config.imageNameOrURLString = model?.start ?? ""
//                config.openModel = ""
//                XHLaunchAd.imageAd(with: config, delegate: self)
//            })

        return true
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .allButUpsideDown
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return WXApi.handleOpen(url, delegate: self) || TencentOAuth.handleOpen(url)
    }
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }
    
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        
    }
}

extension AppDelegate {
    private func getWindow() -> UIWindow {
        UIBarButtonItem.appearance().setTitleTextAttributes([.foregroundColor : UIColor.clear], for: .normal)
        UIBarButtonItem.appearance().setTitleTextAttributes([.foregroundColor : UIColor.clear], for: .highlighted)
        
        let win = UIWindow(frame: UIScreen.main.bounds)
        win.makeKeyAndVisible()
        win.rootViewController = XS_RootVC()
        return win
    }
    
    /// 注册分享登录
    private func registerShare() {
        WXApi.registerApp(XS_Type.wx_appId, universalLink: XS_Type.wx_universalLink)
        _ = TencentOAuth(appId: XS_Type.qq_appId, andUniversalLink: XS_Type.qq_appKey, andDelegate: self)
    }
}

extension AppDelegate: WXApiDelegate {
    func onResp(_ resp: BaseResp) {
        switch resp {
        case let resp as SendAuthResp:
            switch resp.errCode {
            case WXSuccess.rawValue:  // 授权成功
                guard let code = resp.code else {
                    xsWindow()?.makeToast("授权失败")
                    return
                }
                let param = [
                    "appid" : XS_Type.wx_appId,
                    "secret" : XS_Type.wx_appSecret,
                    "code" : code,
                    "grant_type" : "authorization_code"
                ]
                _ = json(.get, "https://api.weixin.qq.com/sns/oauth2/access_token", parameters: param, headers: HTTPHeaders([:]))
                    .observe(on: MainScheduler.instance)
                    .subscribe(onNext: { resp in
                        let model = XS_WeixinM.deserialize(from: resp as? [String:Any])
                        NotificationCenter.default.post(name: Notification.Name("XS_WeixinM"), object: model)
                    })
            case WXErrCodeUserCancel.rawValue: window?.makeToast("取消授权")
            case WXErrCodeAuthDeny.rawValue: window?.makeToast("拒绝授权")
            default: window?.makeToast("授权失败")
            }
        case let resp as SendMessageToWXResp:
            switch resp.errCode {
            case WXSuccess.rawValue: window?.makeToast("恭喜您，分享成功")
            case WXErrCodeUserCancel.rawValue: window?.makeToast("分享取消")
            default: window?.makeToast("抱歉，分享失败")
            }
        case let resp as PayResp: xsDebug { print(resp.errStr) } //TODO: --- 微信支付回调
        default: break
        }
    }
}
extension AppDelegate: TencentSessionDelegate {
    func tencentDidLogin() {}
    func tencentDidNotLogin(_ cancelled: Bool) {}
    func tencentDidNotNetWork() {}
}
